//
//  GZ_SearchViewController.m
//  B段项目
//
//  Created by 高哲 on 15/11/6.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "GZ_SearchViewController.h"
#import "SearchTableViewCell.h"
#import "XMN_ReadDetailViewController.h"
#import "GZ_PlayerPageVC.h"
#import "XMN_PostsViewController.h"
@interface GZ_SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UISearchBar *searchBar;
@property(nonatomic, strong)UIBarButtonItem *cancelButton;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)MBProgressHUD *HUD;


@property(nonatomic, strong)NSMutableArray *dataScourceArray;
@end

@implementation GZ_SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100 * FitWidth, 50 * FitHeight)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"搜索";
    self.navigationItem.titleView = _searchBar;
    
    _cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
    _cancelButton.tintColor = [UIColor grayColor];
    self.navigationItem.rightBarButtonItem = _cancelButton;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView NightWithType:UIViewColorTypeNormal];
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
    myView *headerView = [[myView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 60 * FitHeight + 1)];
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * FitWidth, 0, ScreenWidth, 60 * FitHeight)];
    textLabel.text = @"人气推荐";
    textLabel.textAlignment = NSTextAlignmentLeft;
    textLabel.textColor = [UIColor lightGrayColor];
    textLabel.font = [UIFont systemFontOfSize:18];
    textLabel.font = [UIFont boldSystemFontOfSize:17];
    [headerView addSubview:textLabel];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, textLabel.frame.size.height, ScreenWidth, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    [headerView addSubview:lineView];
    
    _tableView.tableHeaderView = headerView;
    
    [super viewDidLoad];
    self.title = @"阅读";
    
    _HUD = [[MBProgressHUD alloc]initWithView:self.view];
    _HUD.labelText = @"Waiting...";
    [_HUD setMode:MBProgressHUDModeIndeterminate];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    [self.view addSubview:_HUD];
    [_HUD show:YES];
}

- (void)loadView
{
    [super loadView];
    [self getData];
    
}
- (void)getData
{
    [HTTPMethod getDataByString:@"http://api2.pianke.me/search/hotlist" BODYDic:[ChangeString changeStringToDictionary:@"client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg"] WithDataBlock:^(id data) {
        _dataScourceArray = [NSMutableArray array];
        
        NSArray *dataArray = [data valueForKey:@"data"];
        
        for (NSDictionary *tempDic in dataArray) {
            _radioModel = [[GZ_RadioModel alloc] init];
            [_radioModel setValuesForKeysWithDictionary:tempDic];
            [_dataScourceArray addObject:_radioModel];
        }
        [_tableView reloadData];
        [_HUD removeFromSuperview];
    }];
}
#pragma mark 点击进入详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    
    if (_dataArray.count == 0) {
        
        if ([[_dataScourceArray[indexPath.row] myType] integerValue]  == 1) {
            XMN_ReadDetailViewController *rd = [[XMN_ReadDetailViewController alloc] init];
            rd.idString = [_dataScourceArray[indexPath.row] contentid];
            rd.titleString = [_dataScourceArray[indexPath.row] title];
            [self.navigationController pushViewController:rd animated:YES];
            
        }else if ([[_dataScourceArray[indexPath.row] myType] integerValue]  == 17)
        {
            GZ_PlayerPageVC *ppvc = [[GZ_PlayerPageVC alloc] init];
            
            ppvc.tingString = [_dataScourceArray[indexPath.row] contentid];
            [self.navigationController pushViewController:ppvc animated:YES];
        }else{
            XMN_PostsViewController *xmn = [[XMN_PostsViewController alloc] init];
            xmn.titleString = [_dataScourceArray[indexPath.row] title];
            xmn.idString = [_dataScourceArray[indexPath.row] contentid];
            [self.navigationController pushViewController:xmn animated:YES];
        }
        
    }
    else
    {
        SHD_SearDataViewController *ssv = [[SHD_SearDataViewController alloc]init];
        ssv.title = [NSString stringWithFormat:@"与%@相关的内容", _searDataArray[indexPath.row]];
        ssv.idString = _searDataArray[indexPath.row];
        [self.navigationController pushViewController:ssv animated:YES];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchString == nil || [_searchString isEqualToString:@""]) {
        
        return _dataScourceArray.count;
    }
    else if(_dataArray.count != 0)
    {
        return _dataArray.count;
    }
    else
    {
        
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60 * FitHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"GZ";
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
        static NSString *searchIden  = @"secrCell";
    UITableViewCell *searCell = [tableView dequeueReusableCellWithIdentifier:searchIden];
    if (!searCell) {
        searCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchIden];
        [searCell NightWithType:UIViewColorTypeNormal];
        searCell.textLabel.textColor = [UIColor lightGrayColor];
    }
    if (_searchString == nil || [_searchString isEqualToString:@""]) {
        if (_dataScourceArray.count != 0) {
            cell.radioModel = _dataScourceArray[indexPath.row];
        }

        
        return cell;
    }
    else if (_dataArray.count != 0)
    {
        
        searCell.textLabel.attributedText = _dataArray[indexPath.row];
        return searCell;
    }
    else
    {
        
        searCell.textLabel.text = @"抱歉,没有您想要的结果";
        
        return searCell;
    }
}

//回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    SHD_SearDataViewController *ssv = [[SHD_SearDataViewController alloc]init];
     ssv.title = [NSString stringWithFormat:@"与%@相关的内容", _searchString];
    ssv.idString = _searchString;
    
    [self.navigationController pushViewController:ssv animated:YES];
    
}
- (void)backKeyboard
{
    [_searchBar resignFirstResponder];
    
    
}
#pragma mark 搜索高亮
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [HTTPMethod getDataByString:@"http://api2.pianke.me/search/suggest" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"auth=&client=1&deviceid=5AA12B08-7AD2-4ED0-B4EB-571025443952&keyword=%@&version=3.0.6", searchText]] WithDataBlock:^(id data) {
        _dataArray = [NSMutableArray array];
        _searDataArray = [NSMutableArray array];
        NSArray *array = [data objectForKey:@"data"] ;
        for (NSDictionary *dic  in array) {
            NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:[dic objectForKey:@"name"]];
            NSRange range =  [[dic objectForKey:@"name"] rangeOfString:searchText];
            [att setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:0.5 green:0.71 blue:0.58 alpha:1], NSForegroundColorAttributeName, nil] range:range ];
            [_searDataArray addObject:[dic objectForKey:@"name"] ];
            [_dataArray addObject:att];
        }
        _tableView.tableHeaderView = [[UIView alloc]init];
//-------------------------------------------
        if (searchText == nil) {
            myView *headerView = [[myView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 60 * FitHeight + 1)];
            UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * FitWidth, 0, ScreenWidth, 60 * FitHeight)];
            textLabel.text = @"人气推荐";
            textLabel.textAlignment = NSTextAlignmentLeft;
            textLabel.textColor = [UIColor lightGrayColor];
            textLabel.font = [UIFont systemFontOfSize:18];
            textLabel.font = [UIFont boldSystemFontOfSize:17];
            [headerView addSubview:textLabel];
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, textLabel.frame.size.height, ScreenWidth, 1)];
            lineView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
            [headerView addSubview:lineView];
            
            _tableView.tableHeaderView = headerView;
        }
        _searchString = searchText;
//------------------------------------------
        
        [_tableView reloadData];
       
    }];
}

- (void)cancelAction
{
    [_searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
